//
//  RankListViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/25.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "RankListViewController.h"

#import "DesignerDetailViewController.h"

#import "RankListCell.h"
#import "UIImage+GradientColor.h"

@interface RankListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIImageView *selectImg;
@property (nonatomic, assign) BOOL isFuns;

@end

@implementation RankListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setTitleView];
    self.dataArray = [NSMutableArray array];
    self.currentPage = 1;
    self.isFuns = YES;
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(99);
    [self.view addSubview:self.tableView];
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
        NSString *imageName = [NSString stringWithFormat:@"%d",i];
        [arr addObject:ImageWithName(imageName)];
    }
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView.mj_header beginRefreshing];
    
    [self getData];
    
    if (_no.length > 0) {
        UIButton *noteBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(50), ScreenX375(27))];
        [noteBtn setTitle:[NSString stringWithFormat:@"%02ld",(long)[_no integerValue]] forState:UIControlStateNormal];
        [noteBtn setTitleColor:REXADECIMALCOLOR(@"#f21934") forState:UIControlStateNormal];
        noteBtn.titleLabel.font = Kfont(14);
        noteBtn.layer.cornerRadius = ScreenX375(13.5);
        noteBtn.layer.borderColor = REXADECIMALCOLOR(@"#f21934").CGColor;
        noteBtn.layer.borderWidth = 1;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:noteBtn];
    }
}

- (void)setTitleView {
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(215), ScreenX375(31))];
    self.navigationItem.titleView = titleView;
    
    UIView *titleBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(215), ScreenX375(31))];
    titleBg.layer.cornerRadius = ScreenX375(15.5);
    titleBg.layer.borderWidth = 0.5;
    titleBg.layer.borderColor = REXADECIMALCOLOR(@"#eaeaea").CGColor;
    titleBg.layer.masksToBounds = YES;
    [titleView addSubview:titleBg];
    
    UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#fd4d4d"),REXADECIMALCOLOR(@"#ff1062")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(120), ScreenX375(31))];
    _selectImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(120), ScreenX375(31))];
    _selectImg.image = bgImg;
    _selectImg.layer.cornerRadius = ScreenX375(15.5);
    _selectImg.clipsToBounds = YES;
    [titleView addSubview:_selectImg];
    
    NSArray *noteArr = @[@"粉丝排行",@"点赞排行"];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(i * ScreenX375(95), 0, ScreenX375(120), ScreenX375(31))];
        [button setTitle:noteArr[i] forState:UIControlStateNormal];
        [button setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateSelected];
        [button setTitleColor:REXADECIMALCOLOR(@"#888888") forState:UIControlStateNormal];
        button.titleLabel.font = Kfont(15);
        if (i == 0) {
            button.selected = YES;
            _selectBtn = button;
        }
        button.tag = 100 + i;
        [button addTarget:self action:@selector(selectType:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:button];
    }
}

- (void)selectType:(UIButton *)button {
    button.selected = YES;
    _selectBtn.selected = NO;
    _selectBtn = button;
    if (button.tag == 100) {
        self.isFuns = YES;
        [UIView animateWithDuration:0.3 animations:^{
            self.selectImg.frame = CGRectMake(0, 0, ScreenX375(120), ScreenX375(31));
        }];
    }else {
        self.isFuns = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.selectImg.frame = CGRectMake(ScreenX375(95), 0, ScreenX375(120), ScreenX375(31));
        }];
    }
    [_tableView.mj_header beginRefreshing];
}

- (void)headerRefresh {
    _currentPage = 1;
    [self getData];
    self.tableView.mj_footer.hidden = NO;
}

- (void)footerRefresh {
    if (_currentPage <= _totalPage) {
        
        _currentPage++;
        [self getData];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
    }else{
        
//        [HttpManager showNoteMsg:@"已经到底啦"];
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        self.tableView.mj_footer.hidden = YES;
    }
}


- (void)getData {
    NSDictionary *parameter = @{@"page":[NSNumber numberWithInteger:_currentPage],@"id":kNSUDefaultReadKey(@"userId"),@"pageSize":@"10"};
    NSString *url = [NSString stringWithFormat:@"%@api/getUserRank",REQUESTHEADER];
    if (!_isFuns) {
        url = [NSString stringWithFormat:@"%@api/getZanRank",REQUESTHEADER];
    }
    [HttpManager postHttpRequestByGet:url andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if (self.currentPage == 1) {
                [self.dataArray removeAllObjects];
            }
            self.totalPage = [successResponse[@"data"][@"pages"] integerValue];
            NSError *error = nil;
            for (NSDictionary *dic in successResponse[@"data"][@"list"]) {
                RankModel *model = [[RankModel alloc] initWithDictionary:dic error:&error];
                [self.dataArray addObject:model];
            }
            if (self.totalPage == self.currentPage) {
                self.tableView.mj_footer.hidden = YES;
            }
            if ([successResponse[@"data"][@"list"] count] == 0) {
                [HttpManager showNoteMsg:@"暂无更多数据"];
                self.tableView.mj_footer.hidden = YES;
            }
            if (self.currentPage == 1 && self.dataArray.count > 0) {
                [self setHead];
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }else if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)setHead {
    RankModel *model = self.dataArray[0];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(213))];
    self.tableView.tableHeaderView = headView;
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(213))];
    bgView.image = ImageWithName(@"背景图");
    [headView addSubview:bgView];
    
    UILabel *noLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(16), ScreenX375(40), ScreenX375(40))];
    noLabel.text = [NSString stringWithFormat:@"%02ld",(long)[model.no integerValue]];
    noLabel.backgroundColor = RGBACOLOR(255, 255, 255, 0.8);
    noLabel.textAlignment = NSTextAlignmentCenter;
    noLabel.font = Kfont(24);
    noLabel.layer.cornerRadius = ScreenX375(20);
    noLabel.textColor = REXADECIMALCOLOR(@"#f5a623");
    [headView addSubview:noLabel];
    
    UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(65)) / 2, ScreenX375(26), ScreenX375(65), ScreenX375(65))];
    headImage.layer.cornerRadius = ScreenX375(32.5);
    headImage.clipsToBounds = YES;
    [headImage sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:nil options:SDWebImageRetryFailed];
    [headView addSubview:headImage];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(107), SCREEN_WIDTH, ScreenX375(18))];
    nameLabel.text = model.nickName;
    nameLabel.font = KBlodfont(16);
    nameLabel.textColor = FONTCOLOR_BLACK;
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:nameLabel];
    
    UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(134), SCREEN_WIDTH, ScreenX375(17))];
    numLabel.textColor = REXADECIMALCOLOR(@"#212121");
    numLabel.font = Kfont(12);
    numLabel.textAlignment = NSTextAlignmentCenter;
    if (self.isFuns) {
        numLabel.text = [NSString stringWithFormat:@"粉丝数:%@",model.fensNum];
    }else {
        numLabel.text = [NSString stringWithFormat:@"点赞数:%@",model.fensNum];
    }
    [headView addSubview:numLabel];
    
    UIButton *concernBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(64)) / 2, ScreenX375(161), ScreenX375(64), ScreenX375(26))];
    if ([model.isFollow integerValue]) {
        [concernBtn setTitle:@"已关注" forState:UIControlStateNormal];
        [concernBtn setTitleColor:REXADECIMALCOLOR(@"#212121") forState:UIControlStateNormal];
        [concernBtn setImage:nil forState:UIControlStateNormal];
        concernBtn.backgroundColor = [UIColor whiteColor];
    }else {
        [concernBtn setTitle:@" 关注" forState:UIControlStateNormal];
        [concernBtn setTitleColor:REXADECIMALCOLOR(@"#ff2469") forState:UIControlStateNormal];
        [concernBtn setImage:ImageWithName(@"添加关注") forState:UIControlStateNormal];
        concernBtn.backgroundColor = [UIColor clearColor];
    }
    concernBtn.titleLabel.font = Kfont(14);
    concernBtn.layer.cornerRadius = ScreenX375(13);
    concernBtn.layer.borderWidth = 1;
    concernBtn.layer.borderColor = REXADECIMALCOLOR(@"#eaeaea").CGColor;
    [concernBtn addTarget:self action:@selector(concern:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:concernBtn];
}

- (void)concern:(UIButton *)concernBtn {
    RankModel *model = self.dataArray[0];
    if ([model.isFollow integerValue]) {
        model.isFollow = @"0";
        [HttpManager showNoteMsg:@"取消关注成功"];
    }else {
        model.isFollow = @"1";
        [HttpManager showNoteMsg:@"关注成功"];
    }
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/concern",REQUESTHEADER] andParameter:@{@"concernId":kNSUDefaultReadKey(@"userId"),@"concernedId":model.Id} success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if ([model.isFollow integerValue]) {
                [concernBtn setTitle:@"已关注" forState:UIControlStateNormal];
                [concernBtn setTitleColor:REXADECIMALCOLOR(@"#212121") forState:UIControlStateNormal];
                [concernBtn setImage:nil forState:UIControlStateNormal];
                concernBtn.backgroundColor = [UIColor whiteColor];
            }else {
                [concernBtn setTitle:@" 关注" forState:UIControlStateNormal];
                [concernBtn setTitleColor:REXADECIMALCOLOR(@"#ff2469") forState:UIControlStateNormal];
                [concernBtn setImage:ImageWithName(@"添加关注") forState:UIControlStateNormal];
                concernBtn.backgroundColor = [UIColor clearColor];
            }
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dataArray.count > 0) {
        return _dataArray.count - 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RankListCell *cell = [RankListCell cellWithTableView:tableView andIndexPath:indexPath];
    if (_dataArray.count > 0) {
        cell.rankModel = _dataArray[indexPath.row + 1];
        RankModel *model = _dataArray[indexPath.row + 1];
        cell.concernClick = ^{
            [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/concern",REQUESTHEADER] andParameter:@{@"concernId":kNSUDefaultReadKey(@"userId"),@"concernedId":model.Id} success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
                if ([status isEqualToString:@"200"]) {
                    if ([model.isFollow integerValue]) {
                        model.isFollow = @"0";
                        model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] - 1];
                        [HttpManager showNoteMsg:@"取消关注成功"];
                    }else {
                        model.isFollow = @"1";
                        [HttpManager showNoteMsg:@"关注成功"];
                        model.fensNum = [NSString stringWithFormat:@"%ld",[model.fensNum integerValue] + 1];
                    }
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }else {
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [HttpManager showFail];
            }];
        };
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RankModel *model = _dataArray[indexPath.row + 1];
    DesignerDetailViewController *vc = [[DesignerDetailViewController alloc] init];
    vc.designerId = model.Id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
